#include "../common/head.h"
#include <sys/socket.h>
#include <sys/types.h>
#include "stdio.h"
#include "string.h"
#include "string.h"
#include "../net/client_socket.h"
#include "../common/CThreadManage.h"

enum{
	MSG_LOGIN_CHAT_CHANNEL = 1000,
	CHAT_JOIN_CHANNEL_SUCCESS,
	CHAT_MSG,//用户发送的消息
	MSG_RECV //发送给用户的消息
};

//用户登录聊天的世界
struct ChaterLoginChatChannel:MsgBase{
        int     user_id;
        char    user_name[20];
        int     login_chat_channel_id;
        char    login_validate_code[16];
        short   world_id;
        ChaterLoginChatChannel(){
                 msg_type = MSG_LOGIN_CHAT_CHANNEL;
                 memset(user_name,0,20);
                 memset(login_validate_code,0,16);
         }
 
 };


/*
//成功登陆聊天的频道
struct ChaterSuccessJoinChannel:MsgBase{
	CHATER_ID 	user_id;
	CHANNEL_ID	channel_id;
	int			time_stamp;
	ChaterSuccessJoinChannel(){
		msg_type = CHAT_JOIN_CHANNEL_SUCCESS;
		msg_size = sizeof(ChaterSuccessJoinChannel);
	}
};
*/
void handler_msg(MsgBase*);

void init_server_log(int argc, char** argv){
	google::ParseCommandLineFlags(&argc,&argv,true);		
	google::InitGoogleLogging(argv[0]);
}

bool is_login;

int main(int argc,char** argv){
	init_server_log(argc,argv);
	
	//omg::CThreadManage::BeginPoolThread(1);
	int port = 1;
	struct sockaddr_in addr;
	socklen_t len;
	
	memset(&addr,0,sizeof(addr));
	addr.sin_family =	AF_INET;
	addr.sin_port = htons(8003);	
	inet_pton(AF_INET,"127.0.0.1",&addr.sin_addr);
	int fd = socket(AF_INET,SOCK_STREAM,0);

	int flag = fcntl(fd, F_GETFL);
	//flag |= O_NONBLOCK;
	fcntl(fd, F_SETFL, flag);
	if(fd != -1){
		int rest = connect(fd,(struct sockaddr*)&addr,sizeof(addr));
		bool is_login = false;
		while(1){
			if(is_login == false){
				struct MsgLogin msg_login;
				msg_login.player_id = 10;
				strncpy(msg_login.pass_word,"firefly",10);
				msg_login.zeit = time(NULL);
				send(fd,(const char*)&msg_login,msg_login.msg_size - 4,0);
				sleep(2);
				send(fd,((const char*)&msg_login)+(msg_login.msg_size-4),4,0);
				VLOG(1)<<"SEND SIZE"<<msg_login.msg_size;
			}
			
			char buffer[64*1024];
	        	int recv_len = ::recv(fd,buffer,64*1024,0);
			if(recv_len > 0 ){
				VLOG(1)<<"RECIVE .......";
				MsgBase* msg_base = (MsgBase*)buffer;
				handler_msg(msg_base);
			}
			sleep(1);
		}
	}else{
		VLOG(1)<<"error connect";
	}
	pthread_exit(NULL);	
	return 1;
}

void	handler_msg(MsgBase* msg){
/*
	int msg_type = msg->msg_type;
	switch(msg_type){
		case 1:
			MsgLoginAck* login_msg = (MsgLoginAck*)msg;
			if(login_msg->ret == 1){
				VLOG(1)<<"Login Success!!";
				is_login = true;
			}
			break;
		case 1000:
			VLOG(1)<<"default msg...";
			break;
		default:
			VLOG(1)<<"ukonuwn msg....";
	}*/
}
